﻿using Kele.Repository;
using Kele.Activity.Models;
using SqlKata;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Kele.Activity.Service
{
    public class FormService
    {

        public async Task<List<Form>> GetFormListAsync()
        {
            var query = new Query().WhereTrue("IsValid");
            var tableName = AppReflection.GetTableName<Form>();
            var cacheKey = AppCache.GetListKey(tableName);
            return await AppRepository.GetAsync<Form>(query,tableName,cacheKey);
        }

        public async Task<Form> GetFormAsync(int id)
        {

            var tableName = AppReflection.GetTableName<Form>();
            var cacheKey = AppCache.GetEntityKey(tableName, id);

            var ret = await AppCache.GetOrCreateAsync(cacheKey,
                    async () =>
                    {

                        var fromItemList = await AppRepository.GetAsync<FormItem>();
                        var form = await AppRepository.FirstOrDefaultAsync<Form>(id);
                        form.Groups = await AppRepository.GetAsync<FormGroup>("FormId", id);
                        foreach (var formGroup in form.Groups)
                        {
                            formGroup.ItemList = new List<FormItem>();
                            var keys = formGroup.Items.Split(",");
                            foreach (var key in keys)
                            {
                                //通过Key获取FormItem
                                var fields = fromItemList.FindAll(x => x.Key == key);
                                //如果只有一条：就是默认的，不区分FormId
                                //如果多条：就根据FromId获取对应的记录
                                var formItem = fields.Count == 1 ? fields.FirstOrDefault() : fields.FirstOrDefault(f => f.FormId == id);
                                if (formItem != null) formGroup.ItemList.Add(formItem);
                            }
                        }
                        return form;
                    }
                );

            return ret;
        }




    }


}